package com.lagou.conntroller;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/7/26.
 * Time: 1:17.
 * Tags: Code, we are serious.
 */

import com.lagou.model.Token;
import com.lagou.model.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @author
 * @create 2020-07-26 1:17
 **/
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @Value("${config.cookie.name.auth}")
    private String cookieTag;

    /*@GetMapping("/register/{email}/{password}/{code}")
    public boolean register(ServerWebExchange exchange,
                            @PathVariable("email") String email,
                            @PathVariable("password") String password,
                            @PathVariable("code") String code) {
        Token token = userService.register(email, password, code);
        if (token != null) {
            ResponseCookie responseCookie = ResponseCookie.from(cookieTag, token.getToken()).build();
            exchange.getResponse().addCookie(responseCookie);
            return true;
        }
        return false;
    }*/
    @GetMapping("/register/{email}/{password}/{code}")
    public ResponseEntity<Boolean> register(@PathVariable("email") String email,
                                              @PathVariable("password") String password,
                                              @PathVariable("code") String code) {
        Token token = userService.register(email, password, code);
        HttpHeaders headers = new HttpHeaders();
        if (token != null) {
            String cookie = new CookieBuilder().setKey(cookieTag)
                    .setValue(token.getToken())
                    .setMaxAge(840000)
                    .setPath("/")
                    .build();
            headers.add("Set-Cookie", cookie);
            return new ResponseEntity<>(true, headers, HttpStatus.OK);
        }
        return new ResponseEntity<>(false, headers, HttpStatus.OK);
    }

    @GetMapping("/isRegistered/{email}")
    public boolean checkRegistered(@PathVariable("email") String email) {
        return userService.isRegistered(email);
    }

    @GetMapping("/login/{email}/{password}")
    public ResponseEntity<String> login(
                        @PathVariable String email,
                        @PathVariable String password) {
        HttpHeaders headers = new HttpHeaders();
        Token token = userService.login(email, password);
        if (token != null) {
            String cookie = new CookieBuilder().setKey(cookieTag)
                    .setValue(token.getToken())
                    .setMaxAge(840000)
                    .setPath("/")
                    .build();
            headers.add("Set-Cookie", cookie);
            return new ResponseEntity<>(token.getEmail(), headers, HttpStatus.OK);
        }
        return new ResponseEntity<>("", headers, HttpStatus.OK);
    }

    @GetMapping("/info/{token}")
    public String getEmailByToken(@PathVariable String token) {
        return userService.getEmailByToken(token);
    }

    @GetMapping("/logout")
    public void logout(ServerHttpResponse response) {
        userService.logout();
        //response.addHeader(cookieTag, "");
    }

    class CookieBuilder {
        private String key;
        private String value;
        private String expires;
        private String domain;
        private String path;

        public CookieBuilder setKey(String key) {
            this.key = key;
            return this;
        }

        public CookieBuilder setValue(String value) {
            this.value = value;
            return this;
        }

        public CookieBuilder setMaxAge(long ms) {
            //cookie的过期日期为GMT格式的时间。
            Date date = new Date(new Date().getTime() + ms);
            SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            this.expires = sdf.format(date);
            return this;
        }

        public CookieBuilder setDomain(String domain) {
            this.domain = domain;
            return this;
        }

        public CookieBuilder setPath(String path) {
            this.path = path;
            return this;
        }

        public String build() {
            StringBuilder sb = new StringBuilder();
            sb.append(this.key);
            sb.append("=");
            sb.append(this.value);
            sb.append(";");
            if (null != this.expires) {
                sb.append("expires=");
                sb.append(this.expires);
                sb.append(";");
            }
            if (null != this.domain) {
                sb.append("domain=");
                sb.append(this.domain);
                sb.append(";");
            }
            if (null != this.path) {
                sb.append("path=");
                sb.append(this.path);
                sb.append(";");
            }
            return sb.toString();
        }
    }
}
